package per.turtle.gateway.service.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.google.code.kaptcha.Producer;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.FastByteArrayOutputStream;
import per.turtle.common.core.constant.CacheConstants;
import per.turtle.common.core.exception.valid.CaptchaException;
import per.turtle.common.core.web.entity.Captcha;
import per.turtle.common.core.web.entity.CommonResult;
import per.turtle.common.redis.service.RedisService;
import per.turtle.gateway.service.ValidateCodeService;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 验证码实现处理
 *
 * @author turtle
 */
@RequiredArgsConstructor
@Service
public class ValidateCodeServiceImpl implements ValidateCodeService {

    private final RedisService redisService;

    private final Producer captchaProducer;

    /**
     * 生成验证码
     */
    @Override
    public CommonResult<?> createCaptcha() throws CaptchaException {
        // 保存验证码信息
        String uuid = IdUtil.simpleUUID();
        String verifyKey = CacheConstants.getCacheKey(CacheConstants.CAPTCHA_CODE_KEY, uuid);

        // 生成验证码
        String capStr;
        capStr = captchaProducer.createText();
        BufferedImage image = captchaProducer.createImage(capStr);

        redisService.setCacheObject(verifyKey, capStr, CacheConstants.CAPTCHA_EXPIRATION, TimeUnit.SECONDS);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            assert image != null;
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            return CommonResult.error(e.getMessage());
        }

        Captcha captcha = new Captcha();
        captcha.setUuid(uuid);
        captcha.setCode(Base64.encode(os.toByteArray()));
        return CommonResult.success(captcha);
    }

    /**
     * 校验验证码
     */
    @Override
    public void checkCaptcha(String code, String uuid) throws CaptchaException {
        if (StrUtil.isEmpty(code)) {
            throw new CaptchaException("验证码不能为空");
        }
        if (StrUtil.isEmpty(uuid)) {
            throw new CaptchaException("验证码已失效");
        }
        String verifyKey = CacheConstants.getCacheKey(CacheConstants.LOGIN_TOKEN_KEY, uuid);
        String captcha = redisService.getCacheObject(verifyKey);
        redisService.deleteObject(verifyKey);

        if (!code.equalsIgnoreCase(captcha)) {
            throw new CaptchaException("验证码错误");
        }
    }

}
